package org.jdragon.springz.core.utils;

import org.jdragon.springz.scanner.BeanContainer;
import org.jdragon.springz.scanner.entry.InjectedObject;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Author JDragon
 * @Date 2021.03.02 下午 10:21
 * @Email 1061917196@qq.com
 * @Des: 已注入类的工具
 */
public class InjectedUtils {

    private static Map<Class, List> cache = new HashMap<>();

    /**
     * 从已注入实例中寻找以某个类为父类的实例
     *
     * @param clazz 需要寻找的实例父类
     * @return 满足要求的实例
     */
    public static <T> List<T> getBeanWithClass(Class<T> clazz) {
        if (cache.containsKey(clazz)) {
            return cache.get(clazz);
        }
        List<T> objects = new LinkedList<>();
        List<InjectedObject> injectedObjectList = BeanContainer.getInjectedObjectList();
        for (InjectedObject injectedObject : injectedObjectList) {
            if (clazz.isAssignableFrom(injectedObject.getClazz())) {
                objects.add((T) injectedObject.getBean());
            }
        }
        cache.put(clazz, objects);
        return objects;
    }
}
